package com.engineering.elink.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.co.BaseCo;
import com.engineering.elink.co.CommentCo;
import com.engineering.elink.common.HessionInfluenceEnum;
import com.engineering.elink.common.Pagination;
import com.engineering.elink.common.ResultType;
import com.engineering.elink.common.TypeEnum;
import com.engineering.elink.dao.BlogMapper;
import com.engineering.elink.dao.CommentMapper;
import com.engineering.elink.dao.CompanyMapper;
import com.engineering.elink.dao.CourseMapper;
import com.engineering.elink.dao.FileMapper;
import com.engineering.elink.dao.JobMapper;
import com.engineering.elink.dao.NewsMapper;
import com.engineering.elink.dao.PraiseMapper;
import com.engineering.elink.dao.SkillMapper;
import com.engineering.elink.dao.ThesisMapper;
import com.engineering.elink.dao.VideoMapper;
import com.engineering.elink.domain.Blog;
import com.engineering.elink.domain.Comment;
import com.engineering.elink.domain.Company;
import com.engineering.elink.domain.Course;
import com.engineering.elink.domain.File;
import com.engineering.elink.domain.Job;
import com.engineering.elink.domain.News;
import com.engineering.elink.domain.Praise;
import com.engineering.elink.domain.Skill;
import com.engineering.elink.domain.Thesis;
import com.engineering.elink.domain.Video;
import com.engineering.elink.service.CoinBalanceService;
import com.engineering.elink.service.CommentService;
import com.engineering.elink.util.MapConvert;

@Service("commentService")
public class CommentServiceImpl implements CommentService {
	@Autowired
	private CommentMapper commentMapper;
	@Autowired
	private BlogMapper blogMapper;
	@Autowired
	private CompanyMapper companyMapper;
	@Autowired
	private PraiseMapper praiseMapper;
	@Autowired
	private JobMapper jobMapper;
	@Autowired
	private FileMapper fileMapper;
	@Autowired
	private ThesisMapper thesisMapper;
	@Autowired
	private NewsMapper newsMapper;
	@Autowired
	private VideoMapper videoMapper;
	@Autowired
	private CourseMapper courseMapper;
	@Autowired
	private SkillMapper skillMapper;
	@Autowired
	private CoinBalanceService coinBalanceService;
	
	@Override
	public Map<String, Object> getTopCommentsByFileId(CommentCo co) {
		Map<String , Object>map= new HashMap<String, Object>();
		
		map.put("list",commentMapper.selectTopCommentsByFileId(co));
		map.put("Pagination", new Pagination(co, commentMapper.selectTopCommentsCount(co)));
		return MapConvert.getMap(ResultType.SUCCESS,map);
	}
	
	@Override
	public Map<String, Object> getAllCommentsByTopId(BaseCo bc, int topId,int type,Date startTime,Date endTime) {
		Map<String , Object>map= new HashMap<String, Object>();
		
		map.put("list",commentMapper.selectAllCommentsByTopId(bc,topId,type,startTime,endTime));
		map.put("Pagination", new Pagination(bc, commentMapper.selectCount(bc,topId,startTime,endTime)));
		return MapConvert.getMap(ResultType.SUCCESS,map);
	}
	
	@Override
	public Map<String, Object> add(Comment comment) {
		Blog blog  = null;
		Company company  = null;
		Job job = null;
		File file = null;
		Thesis thesis = null;
		News news = null;
		Video video = null;
		Course course = null;
		Skill skill = null;
		// 1,往评论表插入数据
		int commentId =  commentMapper.selectMaxCommentId();
		comment.setCommentId(commentId+1);
		comment.setTime(new Date());		
		comment.setParentId(0);//一级评论的父类id为0
		comment.setTopId(0);// 一级评论的层级topId为0
		
		//2,根据外键检查找评论的所有者
		if(comment.getType() == TypeEnum.BLOG.getIndex()){// 博文
			blog = blogMapper.selectByPrimaryKey(comment.getFkId());
			comment.setByUserId(blog.getUserId());
		}else if (comment.getType() == TypeEnum.COMPANY.getIndex()) { // 企业
			company = companyMapper.selectByPrimaryKey(comment.getFkId());
			comment.setByUserId(company.getUserId());
		}else if (comment.getType() == TypeEnum.JOB.getIndex()) { // 职位
			job = jobMapper.selectByPrimaryKey(comment.getFkId());
			comment.setByUserId(job.getCompanyId());
		}else if(comment.getType() ==TypeEnum.FILE.getIndex()){//资料
			file =  fileMapper.selectByPrimaryKey(comment.getFkId());
			comment.setByUserId(file.getUserId());
		}else if(comment.getType() ==TypeEnum.LIBRARY.getIndex()){//论文
			thesis = thesisMapper.selectByPrimaryKey(comment.getFkId());
			comment.setByUserId(thesis.getUserId());
		}else if(comment.getType() ==TypeEnum.NEWS.getIndex()){//资讯
			news = newsMapper.selectByPrimaryKey(comment.getFkId());
			comment.setByUserId(news.getUserId());
		}else if(comment.getType() ==TypeEnum.VIDEO.getIndex()){//视频
		    video = videoMapper.selectByPrimaryKey(Integer.parseInt(comment.getFkId()));
			comment.setByUserId(video.getUploadUserid());
		}else if (comment.getType() == TypeEnum.COURSE.getIndex()) { // 课程
			course = courseMapper.selectByPrimaryKey(Integer.parseInt(comment.getFkId()));
			comment.setByUserId(course.getUserId());
		}else if (comment.getType() == TypeEnum.SKILL.getIndex()) { // 技能
			skill = skillMapper.selectByPrimaryKey(Integer.parseInt(comment.getFkId()));
			comment.setByUserId(skill.getUpdateUserId());
		}
		//3、一个用户只能够评论一次
		int distinctCount =   commentMapper.selectDistinctCount(comment.getFkId(),comment.getUserId(),comment.getByUserId(),comment.getType());
		if(distinctCount>0){
			return MapConvert.getMap(ResultType.COMMENT_ERROR);
		}
		commentMapper.insertSelective(comment);
		//添加影响值
		try{
			coinBalanceService.modifyInfluenceValue(String.valueOf(commentId), HessionInfluenceEnum.ADDCOMMENT.getIndex(), comment.getUserId());
		}catch (Exception e){
			  Logger logger = Logger.getLogger(CommentServiceImpl.class);
			  logger.info("远程添加评论获取影响值失败"+e);
		}
		
		if (comment.getType() == TypeEnum.BLOG.getIndex()) {// 博文
			// 4,更新博客的评论数量
			if(comment.getStar() != 0){//如果星星数为0 评论数不加1
				blog.setCommentCount(blog.getCommentCount() + 1);
				blogMapper.updateByPrimaryKeySelective(blog);
			}
			return MapConvert.getMap(ResultType.SUCCESS,blog.getCommentCount());
			
		} else if (comment.getType() == TypeEnum.COMPANY.getIndex()) { // 企业
			//5，更新企业的评论数量以及星星
			if(comment.getStar() != 0){//如果星星数为0 评论数不加1
				company.setTotalScore(company.getTotalScore()+comment.getStar());
				company.setCommentCount(company.getCommentCount()+1);
				companyMapper.updateByPrimaryKeySelective(company);
			}
			return MapConvert.getMap(ResultType.SUCCESS,company.getCommentCount());
			
		} else if (comment.getType() == TypeEnum.JOB.getIndex()) { // 职位
			//6,更新职位的评论数量
			if(comment.getStar() != 0){//如果星星数为0 评论数不加1
				job.setCommentCount(job.getCommentCount()+1);
				jobMapper.updateByPrimaryKeySelective(job);
			}
			return MapConvert.getMap(ResultType.SUCCESS,job.getCommentCount());
		}else if(comment.getType() ==TypeEnum.FILE.getIndex()){//资料
			//7,更新资料的评论数量
			file.setCommentCount(file.getCommentCount()+1);
			fileMapper.updateByPrimaryKeySelective(file);
			return MapConvert.getMap(ResultType.SUCCESS,file.getCommentCount());
		}else if(comment.getType() ==TypeEnum.LIBRARY.getIndex()){//论文
			//8,更新论文的评论数量
			thesis.setCommentCount(thesis.getCommentCount()+1);
			thesisMapper.updateByPrimaryKeySelective(thesis);
			return MapConvert.getMap(ResultType.SUCCESS,thesis.getCommentCount());
		}else if(comment.getType() ==TypeEnum.NEWS.getIndex()){//资讯
			//9,更新资讯的评论数量
			news.setCommentCount(news.getCommentCount()+1);
			newsMapper.updateByPrimaryKeySelective(news);
			return MapConvert.getMap(ResultType.SUCCESS,news.getCommentCount());
		}else if(comment.getType() ==TypeEnum.VIDEO.getIndex()){//视频
			 //10,更新视频的评论数量
             video.setCommentCount(video.getCommentCount()+1);
             videoMapper.updateByPrimaryKeySelective(video);
			return MapConvert.getMap(ResultType.SUCCESS,video.getCommentCount());
			
		} else if (comment.getType() == TypeEnum.COURSE.getIndex()) { // 课程
			//11，更新课程的评论数量以及星星
			if(comment.getStar() != 0){//如果星星数为0 评论数不加1
				course.setCommentCount(course.getCommentCount()+1);
				courseMapper.updateByPrimaryKeySelective(course);
			}
			return MapConvert.getMap(ResultType.SUCCESS,course.getCommentCount());
			
		} else if (comment.getType() == TypeEnum.SKILL.getIndex()) { // 技能
			//12，更新技能的评论数量以及星星
			if(comment.getStar() != 0){//如果星星数为0 评论数不加1
				skill.setCommentCount(course.getCommentCount()+1);
				skillMapper.updateByPrimaryKeySelective(skill);
			}
			return MapConvert.getMap(ResultType.SUCCESS,skill.getCommentCount());
		} 
		
		return MapConvert.getMap(ResultType.SUCCESS);
	}
	
	@Override
	public Map<String, Object> addReply(String fkId,int commentId, String userId,String content) {
		Comment c = commentMapper.selectByPrimaryKey(commentId);
		if(c != null){
			//一个用户只能够回复一次
			int replyCount = commentMapper.selectReplyCount(c.getFkId(),userId,c.getByUserId(),c.getType());;
			if(replyCount >0){
				return MapConvert.getMap(ResultType.REPLY_ERROR);
			}
			int oldCommentId =  commentMapper.selectMaxCommentId();
			Comment c1 = new Comment();
			c1.setContent(content);
			c1.setTime(new Date());
			c1.setUserId(userId);
			c1.setContent(content);
			c1.setFkId(fkId);
			c1.setCommentId(oldCommentId+1);
			c1.setType(c.getType());
			
			c1.setByUserId(c.getUserId());
			c1.setParentId(c.getCommentId());//父类id为被评论的评论id
			c1.setTopId(c.getTopId()+1);//层级关系
			commentMapper.insertSelective(c1);
			
			if(c.getType()== TypeEnum.BLOG.getIndex()){//博文
				//更新博文的评论数量
				Blog blog = blogMapper.selectByPrimaryKey(c.getFkId());
				blog.setCommentCount(blog.getCommentCount() + 1);
				blogMapper.updateByPrimaryKeySelective(blog);
				return MapConvert.getMap(ResultType.SUCCESS,blog.getCommentCount());
				
			}else if(c.getType()== TypeEnum.COMPANY.getIndex() ||
					c.getType()== TypeEnum.COURSE.getIndex() ||c.getType()== TypeEnum.SKILL.getIndex()){//企业，课程，技能
				//不需要更新企业，课程，技能的评论数量
				return MapConvert.getMap(ResultType.SUCCESS);
			}else if(c.getType()== TypeEnum.JOB.getIndex()){//职位
				//更新职位的评论数量
				Job job = jobMapper.selectByPrimaryKey(c.getFkId());
				job.setCommentCount(job.getCommentCount()+1);
				jobMapper.updateByPrimaryKeySelective(job);
				return MapConvert.getMap(ResultType.SUCCESS,job.getCommentCount());
			}else if(c.getType() ==TypeEnum.FILE.getIndex()){//资料
				//更新资料的评论数量
				File file = fileMapper.selectByPrimaryKey(c.getFkId());
				 file.setCommentCount(file.getCommentCount()+1);
				 fileMapper.updateByPrimaryKeySelective(file);
				 return MapConvert.getMap(ResultType.SUCCESS,file.getCommentCount());
			}else if(c.getType() ==TypeEnum.LIBRARY.getIndex()){//论文
				//更新论文的评论数量
				 Thesis thesis = thesisMapper.selectByPrimaryKey(c.getFkId());
				 thesis.setCommentCount(thesis.getCommentCount()+1);
				 thesisMapper.updateByPrimaryKeySelective(thesis);
				 return MapConvert.getMap(ResultType.SUCCESS,thesis.getCommentCount());
			}else if(c.getType() ==TypeEnum.NEWS.getIndex()){//资讯
				//更新资讯的评论数量
				News news = newsMapper.selectByPrimaryKey(c.getFkId());
				news.setCommentCount(news.getCommentCount()+1);
				newsMapper.updateByPrimaryKeySelective(news);
				return MapConvert.getMap(ResultType.SUCCESS,news.getCommentCount());
			}else if(c.getType() ==TypeEnum.VIDEO.getIndex()){//视频
				 //更新视频的评论数量
				Video video = videoMapper.selectByPrimaryKey(Integer.parseInt(c.getFkId()));
                 video.setCommentCount(video.getCommentCount()+1);
                 videoMapper.updateByPrimaryKeySelective(video);
  				return MapConvert.getMap(ResultType.SUCCESS,video.getCommentCount());
			}
		}else{
			return MapConvert.getMap(ResultType.AUTHORITY_ERROR);
		}
		return MapConvert.getMap(ResultType.SUCCESS);
	}

	@Override
	public synchronized Map<String, Object> addPraise(Praise praise) {
		Praise oldPraise = praiseMapper.select(praise.getCommentId(),praise.getUserId());//点赞/顶只能够二选一
		Comment c  = commentMapper.selectInfo(praise.getCommentId(),praise.getUserId());
		if(oldPraise == null){
			if(c != null){//如果这条评论不是本人的，则可以点赞
				praise.setPraiseTime(new Date());
				praiseMapper.insertSelective(praise);
				//更新评论的顶/踩数量
				if(praise.getType()==1){//顶
					c.setPraiseCount(c.getPraiseCount()+1);
				}else{//踩
					c.setStampCount(c.getStampCount()+1);
				}
				commentMapper.updateByPrimaryKeySelective(c);
				return MapConvert.getMap(ResultType.SUCCESS);	
			}else{
				return MapConvert.getMap(ResultType.AUTHORITY_ERROR);
			}
		}else {
			if(praise.getType() ==oldPraise.getType()){//两次相同的点赞/顶
				//更新评论的顶/踩数量
				if(praise.getType()==1){//顶
					c.setPraiseCount(c.getPraiseCount()-1);
				}else{//踩
					c.setStampCount(c.getStampCount()-1);
				}
				commentMapper.updateByPrimaryKeySelective(c);
				praiseMapper.del(praise.getCommentId(),praise.getUserId());
				
				return MapConvert.getMap(ResultType.CANCLE_PRAISE);
			}else{
				return MapConvert.getMap(ResultType.PRAISE_ERROR);
			}
		}
	}

	@Override
	public Map<String, Object> getEvaluateById(String fkId,Date startTime,Date endTime,int type) {
		return MapConvert.getMap(ResultType.SUCCESS,commentMapper.getEvaluateById( fkId, startTime, endTime,type)); 
	}

	@Override
	public List<Map<String, Object>> getRecentComment(int count) {
		return commentMapper.getRecentComment(count);
	}

	@Override
	public Map<String, Object> getCommentForMe(BaseCo co, String userId) {
		Map<String , Object>map= new HashMap<String, Object>();
		map.put("list",commentMapper.selectCommentForMe(co,userId));
		map.put("Pagination", new Pagination(co, commentMapper.selectCountCommentForMe(userId)));
		return MapConvert.getMap(ResultType.SUCCESS,map);
	}

	@Override
	public Map<String, Object> getMyComment(BaseCo co, String userId) {
		Map<String , Object>map= new HashMap<String, Object>();
		map.put("list",commentMapper.selectMyComment(co,userId));
		map.put("Pagination", new Pagination(co, commentMapper.selectCountMyComment(userId)));
		return MapConvert.getMap(ResultType.SUCCESS,map);
	}
	@Override
	public Map<String, Object> delComment(String userId, int type) {
		return MapConvert.getMap(ResultType.SUCCESS,commentMapper.delComment(userId,type)); 
	}
}
